# Create your views here.

from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.utils.html import linebreaks
from django.template import loader, Context
from django.conf import settings
from django import newforms as forms
from django.core.paginator import ObjectPaginator, InvalidPage

import os, sys, random, re
sys.path.insert(0, os.path.dirname(__file__))
from models import *

def index_page(request):
    news = News.effective.order_by('-post_date')[0]
    news_title = news.title
    news_content = linebreaks(news.content)
    news_post_date = news.post_date
    news_posted_by = news.posted_by
    
    videos = Video.effective.all()
    show_Videos_list_count = 10
    
    list_video = []
    list_video_index = []
    if videos.count() <= show_Videos_list_count:
        show_Videos_list_count = videos.count()

    i = 0
    while i < show_Videos_list_count:
        irand = random.randint(0, show_Videos_list_count - 1)
        if irand in list_video_index:
            continue
        list_video_index += [irand]
        video = videos[irand]
        dict_video = {}
        dict_video['id'] = video.id
        dict_video['upload_date'] = video.upload_date
        #dict_video['upload_date'] = video.upload_date.strftime('%B %d, %Y')
        dict_video['title'] = video.title
        list_video += [dict_video]
        i += 1
    
    irand = random.randint(0, show_Videos_list_count - 1)
    video = videos[irand]
    dict_video = {}
    dict_video['video_titel'] = video.title
    dict_video['video_description'] = video.description
    dict_video['embed_link'] = video.embed_link
    dict_video['upload_date'] = video.upload_date
    
    
    t = loader.get_template('index.html')
    c = Context({
        'news_title': news_title,
        'news_content': news_content,
        'news_posted_by': news_posted_by,
        'news_post_date': news_post_date,
        'list_video': list_video,
        'dict_video': dict_video,
    })
    return HttpResponse(t.render(c))
    

def vedio_page(request, id):
    try:
        video = Video.effective.get(id = id)
        video_titel = video.title
        video_description = linebreaks(video.description)
        embed_link = video.embed_link
        upload_date = video.upload_date
        video_categories = ','.join([value['name'] for value in video.categories.values() if value['suspended'] == False])
        video_tags = ','.join([value['name'] for value in video.tags.values() if value['suspended'] == False])
    except InvalidPage: 
        raise Http404

    t = loader.get_template('video.html')
    c = Context({
        'video_titel': video_titel,
        'video_description': video_description,
        'upload_date': upload_date,
        'embed_link': embed_link,
        'video_categories': video_categories,
        'video_tags': video_tags,
    })
    return HttpResponse(t.render(c))
   
    
def recent(request, filter = ''):
    list_video = []
    videos = Video.effective.order_by('-upload_date')
    
    if filter:
        try:
            slug = Slug.objects.get(name_type__iexact = filter)
            if re.match('^.+-category$', filter, re.I):
                categories = Category.objects.get(slug = slug)
                videos = videos.filter(categories = categories)
            elif re.match(r'^.+-tag$', filter, re.I):
                tags = Tag.objects.get(slug = slug)
                videos = videos.filter(tags = tags)
            else:
                raise Http404
        except:
            raise Http404
    
    paginator = ObjectPaginator(videos, 20)
    try:
        page = int(request.GET.get('page', '1'))
        videos = paginator.get_page(page - 1)
    except InvalidPage: 
        raise Http404


    list_categories = [{'slug': '', 'name': 'all'}]
    for value in Category.effective.all():
        dict_temp = {}
        dict_temp['name'] = value.name
        dict_temp['slug'] = value.slug.name_type + '/'
        list_categories += [dict_temp]
        
    list_tags = [{'slug': '', 'name': 'all'}]
    for value in Tag.effective.all():
        dict_temp = {}
        dict_temp['name'] = value.name
        dict_temp['slug'] = value.slug.name_type + '/'
        list_tags += [dict_temp]
    
    for video in videos:
        dict_video = {}
        dict_video['id'] = video.id
        #dict_video['upload_date'] = video.upload_date.strftime('%B %d, %Y')
        dict_video['upload_date'] = video.upload_date
        dict_video['title'] = video.title
        list_video += [dict_video]
        
    t = loader.get_template('recent.html')
    c = Context({
        'list_video': list_video, 
        'has_next': paginator.has_next_page(page - 1),
        'has_previous': paginator.has_previous_page(page - 1),
        'current_page': page,
        'next_page': page + 1,
        'previous_page': page - 1,
        'pages': paginator.pages,
        'list_categories': list_categories,
        'list_tags': list_tags,
    })
    return HttpResponse(t.render(c))
    

def sub_video(request, id=None):
    Message = ''
    uploader_name = ''
    title = ''
    tags = ''
    description = ''
    video_link = ''
    if request.method == 'GET':
        if request.GET.get('sub', False):
            if request.GET['sub'] == 'true':
                Message = 'Submitted videos success'
    
    if request.method == 'POST':
        uploader_name = request.POST.get('uploader_name', '')
        title = request.POST.get('title', '')
        tags = request.POST.get('tags', '')
        description = request.POST.get('description', '')
        video_link = request.POST.get('video_link', '')
        
        if not uploader_name:
            Message = 'Please input uploader name'
        elif not title:
            Message = 'Please input title'
        elif not video_link:
            Message = 'Please input video link'
        elif not re.match(r'^http://([\w-]+\.)+[\w-]+(/[-\w\d //%&=]*)?$', video_link, re.I):
            Message = 'URL format error'
        else:
            video = Submitted_Video()
            video.uploader_name = uploader_name
            video.title = title
            video.tags = tags
            video.description = description
            video.video_link = video_link
            video.client_ip_address = request.META['REMOTE_ADDR']
            video.status = 'processing'
            video.save()
            return HttpResponseRedirect("/submit-video/?sub=true")
        """
    elif request.method == 'GET':
        form = SubmittedForm(request.GET)
        if form.is_valid():
            submitted = form.save(commit = False)
            #if id is None:
            #    entry.owner = request.user
            submitted.save()
            return HttpResponseRedirect("/submit-video/")"""
    
    t = loader.get_template('sub_video.html')
    c = Context({
        'uploader_name': uploader_name,
        'title': title,
        'tags': tags,
        'description': description,
        'video_link': video_link,
        'Message': Message,
    })
    return HttpResponse(t.render(c))
    

def contact_us(request, id = None):
    Message = ''
    name = ''
    email = ''
    content = ''
    if request.method == 'GET':
        if request.GET.get('sub', False):
            if request.GET['sub'] == 'true':
                Message = 'Submitted contact success'
    
    if request.method == 'POST':
        name = request.POST.get('name', '')
        email = request.POST.get('email', '')
        content = request.POST.get('content', '')
        
        if not name:
            Message = 'Please input name'
        elif not email:
            Message = 'Please input email'
        elif not re.match('^[a-z]([a-z0-9]*[-_]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[\.][a-z]{2,3}([\.][a-z]{2})?$',
            email, re.I):
            Message = 'Email format error'
        elif not content:
            Message = 'Please input content'
        else:
            contact = Submitted_Feedback()
            contact.name = name
            contact.email = email
            contact.content = content
            contact.client_ip_address = request.META['REMOTE_ADDR']
            contact.save()
            return HttpResponseRedirect('/contact-us/?sub=true')
    t = loader.get_template('contact_us.html')
    c = Context({
        'name': name,
        'email': email,
        'content': content,
        'Message': Message,
    })
    return HttpResponse(t.render(c))

